<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item
              label="投料记录单号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="feedingRecordCode"
            >
              <a-input v-model="model.feedingRecordCode" disabled placeholder="请输入投料记录单号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="配方号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaNumber">
              <j-search-select-tag
                type="list"
                v-model="model.formulaNumber"
                :dictOptions="formulaNumberOptions"
                placeholder="请选择配方号"
                @change="handleChangeFormulaNumber"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab=" " :key="refKeys[0]" :forceRender="true">
        <a-row :gutter="20" style="margin-bottom: 5px" v-if="!formDisabled">
          <a-col :span="2">
            <a-button @click="handleAddMaterial" type="primary" icon="plus">新增物料</a-button>
          </a-col>
        </a-row>
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="erpProductionFeedingAfterDetailTable.loading"
          :columns="erpProductionFeedingAfterDetailTable.columns"
          :dataSource="erpProductionFeedingAfterDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true" 
          :toolbarConfig="{ slot: ['prefix', 'suffix'], btn: ['remove', 'clearSelection'] }"
        />
      </a-tab-pane>
    </a-tabs>
    <!-- 该车间仓库下的物料列表 -->
  <material-list-modal  ref="materialListModal" @ok="selectMaterial"/>
  </a-spin>
</template>

<script>
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getAction, putAction } from '@/api/manage'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import MaterialListModal from '../../feedingbefore/modules/MaterialListModal.vue'

export default {
  name: 'ErpProductionFeedingAfterForm',
  mixins: [JVxeTableModelMixin],
  components: {MaterialListModal},
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        feedingRecordCode: '',
        workshopCode: '',
        planId: '',
        packshopCode: '',
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 0,
      addRowBtn: false,
      validatorRules: {
        feedingRecordCode: [{ required: true, message: '投料记录单号不能为空!' }],
      },
      refKeys: ['erpProductionFeedingAfterDetail'],
      tableKeys: ['erpProductionFeedingAfterDetail'],
      activeKey: 'erpProductionFeedingAfterDetail',
      // 投料记录明细
      erpProductionFeedingAfterDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料编码',
            key: 'materialCode',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '规格型号',
            key: 'materialSpec',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '主计量单位',
            key: 'meUnit',
            dictCode: 'ji_unit',
            type: JVXETypes.select,
            width: '200px',
            disabled: true,
            defaultValue: '',
          },
          {
            title: '主数量',
            key: 'meNum',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '辅计量单位',
            key: 'auUnit',
            dictCode: 'zl_unit',
            type: JVXETypes.select,
            width: '200px',
            disabled: true,
            defaultValue: '',
          },
          {
            title: '辅数量',
            key: 'auNum',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '批次号',
            key: 'batchNo',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '物料批号',
            key: 'materialBatchNo',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '库存数量',
            key: 'stockNum',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '投料数量',
            key: 'feedingNum',
            type: JVXETypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            validateRules: [{ required: true, message: '${title}不能为空' }],
            defaultValue: '',
            fixed: 'right',
          },
        ],
      },
      url: {
        add: '/feedingafter/erpProductionFeedingAfter/add',
        edit: '/feedingafter/erpProductionFeedingAfter/edit',
        queryById: '/feedingafter/erpProductionFeedingAfter/queryById',
        erpProductionFeedingAfterDetail: {
          list: '/feedingafter/erpProductionFeedingAfter/queryErpProductionFeedingAfterDetailByMainId',
          tslProWorkshopPlanDetail: '/pro/tslProWorkshopPlan/queryWorkshopPlanInfoByMainId',
        },
        //获取配方号下拉数据
        formulaNumberList: '/feedingbefore/erpProductionFeedingBefore/queryFormulaNumberByPlanIds',
      },
      // 配方号下拉
      formulaNumberOptions: [],
      workshopPlanList: [],
      // 配方编号
      formulaCode: '',
      formulaNumberMap: {},
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    //新增功能的传值
    confirmationData: {
      type: Object,
      default: () => ({}),
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {},
  methods: {
    addAfter() {
      // this.getMaterialDetailList()
      this.erpProductionFeedingAfterDetailTable.dataSource = []
      this.getSequenceNum()
      this.loadFormulaNumberOptions(this.confirmationData.planId)
      this.model.workshopCode = this.confirmationData.workshopCode
      this.model.planId = this.confirmationData.planId
      this.model.planCode = this.confirmationData.planCode
      this.model.workTime = this.confirmationData.workTime
    },
    add() {
      // 执行自定义的addAfter逻辑
      if (typeof this.addAfter === 'function') this.addAfter()
      
      // 跳过原mixin中的自动添加行代码
      // 直接调用edit方法打开弹窗
      this.edit(this.model)
      
      // 执行自定义的addAfter逻辑
      if (typeof this.addAfter === 'function') this.addAfter(this.model)
    },
    // 重写编辑方法，确保不会添加行
    edit(record) {
      if (typeof this.editAfter === 'function') this.editAfter(record)
      this.visible = true
      this.activeKey = this.refKeys[0]
      this.model = Object.assign({}, record)
      
      // 跳过原mixin中的自动添加行逻辑
      // 直接执行编辑后回调
      if (typeof this.editAfter === 'function') this.editAfter(this.model)
    },
    //获取投料记录单号
    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/production_feeding_code'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.feedingRecordCode = res.result
        }
      })
    },
    // 获取新增窗口配方号下拉
    loadFormulaNumberOptions(ids) {
      this.formulaNumberOptions = []
      this.formulaNumberMap = {} // 初始化映射
      getAction(this.url.formulaNumberList, { ids }).then((res) => {
        if (res.success) {
          // 构建映射关系：value(配方号) -> formulaCode(配方编号)
          res.result.forEach(item => {
            this.formulaNumberMap[item.text] = item.value
          })
          this.formulaNumberOptions = res.result.map((item) => ({
            value: item.text,
            text: item.text,
            // 保留配方编号用于后续访问
            formulaCode: item.value 
          }))
          // 默认选择第一条并设置配方编号
          if (this.formulaNumberOptions.length > 0 && !this.model.formulaNumber) {
            const firstOption = this.formulaNumberOptions[0]
            this.model.formulaNumber = firstOption.text
            this.formulaCode = firstOption.formulaCode // 存储配方编号
          }
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //获取物料信息
    getMaterialDetailList() {
      this.erpProductionFeedingAfterDetailTable.dataSource = []
      this.formulaNumberOptions = []
      getAction(this.url.erpProductionFeedingAfterDetail.tslProWorkshopPlanDetail, {
        id: this.confirmationData.planId,
      }).then((res) => {
        if (res.success) {
          let dataSource = res.result || res.result.records
          this.workshopPlanList = dataSource
          if (dataSource.length > 0) {
            this.formulaNumberOptions = dataSource.map((item) => ({
              value: item.formulaNumber,
              text: item.formulaNumber,
            }))
            this.model.formulaNumber = dataSource[0].formulaNumber
            if (dataSource[0].tslProScheduleDetail) {
              this.erpProductionFeedingAfterDetailTable.dataSource = dataSource[0].tslProScheduleDetail.map(
                (item) => ({
                  materialCode: item.productCode,
                  materialName: item.productBatchNo,
                  materialSpec: item.materialSpec,
                  meUnit: item.meUnit,
                  meNum: item.mainQuantity,
                  auUnit: item.auUnit,
                  auNum: item.auxiliaryQuantity,
                  stockNum: item.stockQuantity,
                })
              )
            }
          }
        }
      })
    },
    handleChangeFormulaNumber() {
      if (!this.model.formulaNumber) {
        this.erpProductionFeedingAfterDetailTable.dataSource = []
        this.formulaCode = '' // 清空配方编号
        return
      }
      // 从映射中获取当前配方号对应的配方编号
      this.formulaCode = this.formulaNumberMap[this.model.formulaNumber] || ''
      // 清空子表数据源
      this.erpProductionFeedingAfterDetailTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id && this.model.planId) {
        let params = {
          // feedingRecordId: this.model.id,
          // planId: this.model.planId,
          id: this.model.id,
        }
        this.requestSubTableData(
          this.url.erpProductionFeedingAfterDetail.list,
          params,
          this.erpProductionFeedingAfterDetailTable
        )
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    // 修改classifyIntoFormData方法 目的是为了删除自动生成的row_id字段
    classifyIntoFormData(allValues) {
      // 先获取原始表单数据
      const formData = {
        ...this.model,
        ...allValues.formValue,
        erpProductionFeedingAfterDetailList: allValues.tablesValue[0].tableData,
      }
      // 处理子表数据：移除自动生成的临时ID
      if (formData.erpProductionFeedingAfterDetailList && formData.erpProductionFeedingAfterDetailList.length > 0) {
        formData.erpProductionFeedingAfterDetailList = formData.erpProductionFeedingAfterDetailList.map((item) => {
          // 删除临时生成的id字段
          if (item.id && item.id.startsWith('row_')) {
            const { id, ...rest } = item
            return rest
          }
          return item
        })
      }
      return formData
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    // 点击新增，查询该车间仓库下的物料列表
    handleAddMaterial() {
      // 检查是否选择了配方号
      if (!this.model.formulaNumber) {
        this.$message.warning('请先选择配方号')
        return
      }
      // 打开物料列表弹窗，传递配方号和生产车间
      this.$refs.materialListModal.add({
        planCode: this.model.planCode,
        formulaCode: this.formulaCode,
        formulaNumber: this.model.formulaNumber,
        workshopCode: this.model.workshopCode
      })
    },
    //保存物料
    selectMaterial(selectedMaterials) {
      // 将选择的物料添加到子表
      if (selectedMaterials && selectedMaterials.length > 0) {
        const newRows = selectedMaterials.map(material => ({
          materialCode: material.materialCode,
          materialName: material.materialName,
          materialSpec: material.specificationModel,
          meUnit: material.unit, 
          meNum: material.quantity, 
          auUnit: material.secondaryUnit, 
          auNum: material.secondaryQuantity, 
          batchNo: material.batchNumber,
          materialBatchNo: material.materialBatchNumber,
          stockNum: material.quantity,
          inventoryId: material.id,
          feedingNum: '' // 投料数量
        }))
        const tableRef = this.$refs[this.refKeys[0]];
        if (tableRef) {
          tableRef.addRows(newRows);
        }
      }
    },
  },
}
</script>

<style scoped></style>
